package com.lc.usercenter.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.usercenter.common.ErrorCode;
import com.lc.usercenter.exception.BusinessException;
import com.lc.usercenter.mapper.UserMapper;
import com.lc.usercenter.model.domain.User;
import com.lc.usercenter.model.domain.request.UserRegisterRequest;
import com.lc.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.lc.usercenter.constant.UserConstant.*;

/**
 * @author 罗超
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-11-20 01:37:36
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String SALT = "lc";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserMapper userMapper;

    /**
     * 发送验证码
     * @param phone 手机号码
     * @return boolean
     */
    @Override
    public Boolean sendCode(String phone) {
        // 1. 校验手机号是否合法
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入手机号码");
        }
        Matcher matcher = Pattern.compile(PHONE_VALID_PATTERN).matcher(phone);
        if (!matcher.matches()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入正确的手机号码");
        }

        // 2. 系统生成6位的随机数
        String code = RandomUtil.randomNumbers(6);
        // 存到redis中,手机号为key存储code,设置过期时间
        stringRedisTemplate.opsForValue().set(VERIFICATION_CODE+phone,code,TIMEOUT, TimeUnit.MINUTES);
        log.info("registerCode:{}",code);
        // 4. todo 调用阿里短信服务

        return true;
    }
    /**
     * 用户注册
     * @param userRegisterRequest 用户信息
     * @param validCode 验证码
     * @return
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest,String validCode) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planeCode = userRegisterRequest.getPlanetCode();
        String phone = userRegisterRequest.getPhone();
        // 判断是否为空
        if (StringUtils.isAnyEmpty(userAccount, userPassword, checkPassword,planeCode,validCode)) {
            // todo 修改为自定义异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"信息不能为空");
        }

        // 判断账户名是否小于4
        if (userAccount.length() < 4) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名长度不能小于4");
        }
        // 判断密码是否小于8
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8");
        }
        Matcher matcherPhone = Pattern.compile(PHONE_VALID_PATTERN).matcher(phone);
        if (!matcherPhone.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入正确的手机号码");
        }
        //校验验证码是否正确
        String validRedisCode = stringRedisTemplate.opsForValue().get(VERIFICATION_CODE + phone);
        if (!validRedisCode.equals(validCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码错误！");
        }
        // 不能包括特殊字符
        String validPattern = "^[a-zA-Z0-9_.]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名不能包含特殊字符");
        }
        // 密码与校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"账户名或密码不正确");
        }
        // 账户唯一
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户已存在");
        }
        // 编码唯一
        QueryWrapper<User> queryPlanetCode = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planeCode);
        count = userMapper.selectCount(queryPlanetCode);
        if (count < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编码已存在");
        }
        // 密码加密
        userPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 存入数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        user.setPlanetCode(planeCode);
        user.setPhone(phone);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * @param userAccount  账户名
     * @param userPassword 密码
     * @param request 请求体
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 判断是否为空
        if (StringUtils.isAnyEmpty(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名和密码不能为空");
        }
        // 判断账户名是否小于4
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名长度不能小于4");
        }
        // 判断密码是否小于4
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8");
        }
        // 不能包括特殊字符
        String validPattern = "^[a-zA-Z0-9_.]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名不能包含特殊字符");
        }
        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 密码是否正确
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名或密码错误");
        }
        // 脱敏
        User safatyUser = getSafatyUser(user);
        // 记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safatyUser);
        return safatyUser;
    }

    /**
     * 用户注销
     * @param request 请求体
     * @return Integer
     */
    @Override
    public Integer logout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 脱敏
     * @param user 查询的用户
     * @return 脱敏后的用户
     */
    @Override
    public User getSafatyUser(User user){
        User safatyUser = new User();
        safatyUser.setId(user.getId());
        safatyUser.setUserName(user.getUserName());
        safatyUser.setUserAccount(user.getUserAccount());
        safatyUser.setUserAvatar(user.getUserAvatar());
        safatyUser.setGender(user.getGender());
        safatyUser.setUserRole(user.getUserRole());
        safatyUser.setUserStatus(user.getUserStatus());
        safatyUser.setCreateTime(user.getCreateTime());
        return safatyUser;
    }



}